package Locomotive;

import java.awt.AlphaComposite;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import javax.swing.JPanel;

/**
 *
 * @author Mikael Köhlmyr | mikael@kohlmyr.com | http://www.kmyr.net
 */
public class Screen extends JPanel{
    // 3, 23 offset!?
    private static final int NUM_PARTICLES = 1;
    public static final int OFF_X = 3, OFF_Y = 23;
    public static final int WIDTH = 680, HEIGHT = 410;
    private static boolean run;
    //public static int CONTROL;
    private volatile static Image buffer;
    private volatile static Image background;
    public volatile static Graphics2D bufferg;
    public volatile static Graphics backgroundg;
    private static Particle[] particles =  new Particle[Screen.NUM_PARTICLES];

    public Screen(){
    }

    public void configure(){
        Screen.buffer = new BufferedImage(Screen.WIDTH, Screen.HEIGHT, BufferedImage.TYPE_INT_ARGB);
        Screen.bufferg = (Graphics2D)Screen.buffer.getGraphics();
        //Screen.background = new BufferedImage(Screen.WIDTH, Screen.HEIGHT, BufferedImage.TYPE_INT_RGB);
        //Screen.backgroundg = Screen.background.getGraphics();
        //this.draw_background();
        for(int i = 0; i < Screen.NUM_PARTICLES; i++){
            particles[i] = new Particle();
            particles[i].configure();
        }
        new Thread(new ParticleManager()).start();
    }
//    public void draw_background(){
//        Screen.backgroundg.setColor(Color.BLACK);
//        Screen.backgroundg.fillRect(0, 0, Screen.WIDTH, Screen.HEIGHT);
//    }


    @Override
    public void paintComponent(Graphics g){
        super.paintComponent(g);
        g = (Graphics2D)g;
        g.setColor(Color.BLACK);
        g.fillRect(0, 0, Screen.WIDTH, Screen.HEIGHT);
        g.drawImage(Screen.buffer, 0, 0, this);
    }

    private class ParticleManager implements Runnable{
        public void run() {
            while(true){
                ((BufferedImage)buffer).createGraphics().clearRect (0, 0, Screen.WIDTH, Screen.HEIGHT);
                for(Particle p : particles){
                    p.wake_up();
                }
                try {
                    Thread.sleep((long) Physics.FRAME_LENGTH/2);

                } catch (InterruptedException ex) {
                    Util.print_exception(ex);
                }
                repaint();
                try {
                    Thread.sleep((long) Physics.FRAME_LENGTH/2);
                } catch (InterruptedException ex) {
                    Util.print_exception(ex);
                }
            }
        }
    }
}